import axios from 'axios'
import qs from 'qs'
import config from './config.js'
import LRU from 'lru-cache'
import md5 from 'md5'

const cached = LRU({max: 1000, maxAge: 1000 * 60 * 15})

var api = axios.create(config)

api.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

api.interceptors.response.use(response => {
  return response.data
}, error => {
  let err = error.response.data
  return Promise.reject(err)
})

export default {
  post (url, data) {
    return api({
      method: 'post',
      url,
      data: data
    })
  },
  postForm (url, data) {
    return api({
      method: 'post',
      url,
      data: qs.stringify(data),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
  },
  get (url, params) {
    const key = md5(url + JSON.stringify(params))
    if (cached.has(key)) {
      return Promise.resolve(cached.get(key))
    }
    return api({
      method: 'get',
      url,
      params
    }).then(res => {
      cached.set(key, res)
      return res
    })
  }
}
